

Q = require('q');

/*
function f1(cb1,cb2){
    console.log('f1 start');
    setTimeout(function(){console.log('f1 end');cb1(cb2)},5000)

}

function f2(cb){
    console.log('f2 start')
    setTimeout(function(){console.log('f2 end');cb()},5000)
}

function f3(){
    console.log('f3 start')
}

f1(f2,f3)
*/





function f1(type,cb){
    console.log('f1 start');
    setTimeout(function(){cb(type)},5000)

}

function f2(type,cb){
    console.log('f2 start');
    setTimeout(function(){cb(type)},5000)

}

function f3(type,cb){
    console.log('f3 start');
    setTimeout(function(){cb(type)},5000)

}

function f1_q(type){
    var deferred= Q.defer();
    f1(type,function(result){
        if(result==1){
            deferred.resolve(result)
        }
        else {
            deferred.reject('slkdjfalksdjf;aksdjf;lkasd');
        }
    })

    return deferred.promise;
}

function f2_q(type){
    var deferred= Q.defer();
    f2(type,function(result){
        if(result==1){
            deferred.resolve(result)
        }
        else {
            deferred.reject(result);
        }
    })

    return deferred.promise;
}


function f3_q(type){
    var deferred= Q.defer();
    f3(type,function(result){
        if(result==1){
            deferred.resolve(result)
        }
        else {
            deferred.reject(result);
        }
    })

    return deferred.promise;
}





f1_q(0)
    .then(function(){return f2_q(1)})   //promise reject
    .then(function(){return f3_q(1)})
    .fail(function(result){console.log('fail',result)});



function resolve(){
    console.log('resolve')
}
function reject(){
    console.log('reject')
}



